import "../../css/goods.css"

import {
    Col, Row, Button, Input, Checkbox, Table, Tag, Pagination, Tooltip, Skeleton, Image, message
    , Popconfirm, Modal, InputNumber
} from 'antd';
import { AudioOutlined } from '@ant-design/icons';
import { useEffect, useRef, useState } from "react";
import { AddGoods, AddInventory, BanGoods, DeleteGoods, GetGoods, ShelveGoods } from "../../api/goods";
import { useNavigate } from "react-router-dom";



// 搜索框属性 start
const { Search } = Input;
const suffix = (
    <AudioOutlined
        style={{
            fontSize: 16,
            color: '#1677ff',
        }}
    />
);


//搜索框属性 end





const options = [
    {
        label: '直营',
        value: "a",
    },
    {
        label: '禁用',
        value: "b",
    },
    {
        label: '上架',
        value: 'c',
    },
    {
        label: '库存',
        value: 'd',
    }
];
//复选框 end





//商品管理主页
const GoodsIndex = () => {
    document.info = [
        {
            title: "商品管理-主页",
            url: "/goods",
        }]
    // console.log(document.url,"kkkkk");
    //表格数据
    const [tableData, setTable] = useState([]);
    //获取搜索框dom
    const myRef = useRef("");

    const [numbers, setNumbers] = useState(null);
    //分页
    const [pages, setPage] = useState({
        page: 1,
        limit: 10,
        total: 0
    })
    const [load, setLoad] = useState({
        loading: false,
        isFirst: true
    });

    const navigate = useNavigate();
    //下架/上架按钮
    const MyButton = (hang) => {
        if (hang.hang.inventory === 0 && hang.hang.sales === 0 && hang.hang.isShelve === 0 || hang.hang.isBan === 1) {
            return
        } else {
            if (hang.hang.isShelve === 0) {
                return <div className="success btn" onClick={() => { shelveChange(hang.hang, 1) }}>上架</div>
            } else {
                return <div className="warning btn" onClick={() => { shelveChange(hang.hang, 0) }}>下架</div>
            }
        }
    }



    //条件查询条件
    const [likeSelect, setLike] = useState({
        key: "",
        isBan: -1,
        isShelve: -1,
        inventory: -1,
        isDirectly: -1
    });



    //复选框 start
    const onChange = (checkedValues) => {
        setPage((pages) => ({ ...pages, page: 1, limit: 10 }));
        //直营 -1/1
        if (checkedValues.includes("a")) {
            setLike((likeSelect) => ({ ...likeSelect, isDirectly: 1 }));
        } else {
            setLike((likeSelect) => ({ ...likeSelect, isComplete: -1 }));
        }
        //禁用  -1/1
        if (checkedValues.includes("b")) {
            setLike((likeSelect) => ({ ...likeSelect, isBan: 1 }));
        } else {
            setLike((likeSelect) => ({ ...likeSelect, isBan: -1 }));
        }
        //上架 -1/1
        if (checkedValues.includes("c")) {
            setLike((likeSelect) => ({ ...likeSelect, isShelve: 1 }));
        } else {
            setLike((likeSelect) => ({ ...likeSelect, isShelve: -1 }));
        }

        //库存 -1/0
        if (checkedValues.includes("d")) {
            setLike((likeSelect) => ({ ...likeSelect, inventory: 0 }));
        } else {
            setLike((likeSelect) => ({ ...likeSelect, inventory: -1 }));
        }

        if (checkedValues.length === 0) {

            setLike((likeSelect) => ({
                ...likeSelect,
                isBan: -1,
                isShelve: -1,
                inventory: -1,
                isDirectly: -1
            }));
        }


    };

    //跳转详情
    const goodDetail = (props) => {
        console.log(props);
        navigate(`/goods/detail/${props}`);
    }

    const goodZiZhi=(props)=>{
        navigate(`/goods/qualifications/${props}`)
    }


    //表格表头
    const columns = [
        {
            title: '序号',
            dataIndex: 'Index',
            key: 'Index',
            width: 60
        },
        {
            title: '图片',
            dataIndex: 'photo',
            key: 'photo',
            render: (text) => (
                <div>
                    {/* {text} */}
                    <Image src={text} height={60} width={60} alt="" className="good-photo" />
                </div>
            ),
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: 80,
            render: (text) => <Tooltip placement="topLeft" title={text}>{text}</Tooltip>,
            onCell: () => {
                return {
                    style: {
                        maxWidth: 120,
                        overflow: 'hidden',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis',
                        cursor: 'pointer',

                    }
                }
            },
        },

        {
            title: '供应商',
            dataIndex: 'supplier',
            key: 'supplier',
            width: 80,
            onCell: () => {
                return {
                    style: {
                        maxWidth: 80,
                        overflow: 'hidden',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis',
                        cursor: 'pointer',

                    }
                }
            },
            render: (text) => (
                <div>
                    {text == null ? <Tag color="red" bordered={false} className="danger-tag">直营</Tag> :
                        <span><Tooltip placement="topLeft" title={text}>{text.length > 4 ? text.substring(0, 4) + "..." : text}</Tooltip></span>}
                </div>
            ),
        },
        {
            title: '单价',
            dataIndex: 'price',
            key: 'price',
            width: 90,
            onCell: () => {
                return {
                    style: {
                        maxWidth: 120,
                        overflow: 'hidden',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis',

                    }
                }
            },
            render: (text) => (
                <div><Tag color="red" className="danger-tag" bordered={false}>￥ {text}</Tag></div>
            ),
        },
        {
            title: '库存总数',
            dataIndex: 'inventory',
            key: 'inventory',
            width: 90,
            render: (text) => (
                <div><Tag color="blue" className="primary-tag" bordered={false}>{text}</Tag></div>
            ),
        },
        {
            title: '库存总数',
            dataIndex: 'inventory',
            key: 'inventory',
            width: 90,
            render: (text, hang) => (
                <div><Tag color="blue" className="primary-tag" bordered={false}>{text - hang.sales}</Tag></div>
            ),
        },
        {
            title: '销量',
            dataIndex: 'sales',
            key: 'sales',
            width: 90,
            render: (text) => (
                <div><Tag color="blue" className="primary-tag" bordered={false}>{text}</Tag></div>
            ),
        },
        {
            title: '生产日期',
            dataIndex: 'birthday',
            key: 'birthday',
            width: 100,
            render: (text) => (
                <div><Tag color="blue" className="primary-tag" bordered={false}>{text}</Tag></div>
            ),
        },
        {
            title: '保质期',
            dataIndex: 'expiryday',
            key: 'expiryday',
            width: 90,
            render: (text) => (
                <div><Tag color="blue" className="primary-tag" bordered={false}>{text}天</Tag></div>
            ),
        },
        {
            title: '剩余天数',
            dataIndex: 'surplus',
            key: 'surplus',
            width: 90,
            render: (text) => {
                if(text>=0){
                   return <div><Tag color="success" className="success-tag" bordered={false}>{text}天</Tag></div>
                }else if(text<0){
                    return <div><Tag color="red" className="danger-tag" bordered={false}>已过期{text.toString().substring(1)}天</Tag></div>
                }
            },
        },
        {
            title: '上架时间',
            dataIndex: 'shelveTime',
            key: 'shelveTime',
            width: 90,
            render: (text) => <Tooltip placement="topLeft" title={text}>{text}</Tooltip>,
            onCell: () => {
                return {
                    style: {
                        maxWidth: 120,
                        overflow: 'hidden',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis',
                        cursor: 'pointer',

                    }
                }
            },
        },
        {
            title: '禁用',
            dataIndex: 'isBan',
            key: 'isBan',
            width: 90,
            render: (text) => (
                <div> {text == 0 ? <Tag color="success" className="success-tag" bordered={false}>否</Tag> : <Tag color="red" className="danger-tag" bordered={false}>是</Tag>}</div>
            ),
        },
        {
            title: '操作',
            dataIndex: '',
            key: '',
            fixed: "right",
            width: 325,
            render: (text, hang) => (
                <div style={{ width: 325 }}>
                    <div style={{ marginLeft: "5px" }} className="success-cell btn" size="small" onClick={() => { goodDetail(hang.id) }}>详情</div>
                    <div type="primary" className="primary btn" style={{ marginLeft: "5px" }} onClick={() => { goodZiZhi(hang.id) }}>资质</div>
                    <Popconfirm
                        title="提示"
                        description="确认将商品删除吗?"
                        onConfirm={() => { confirm(hang.id) }}
                        onCancel={cancel}
                        okText="确定"
                        cancelText="取消"
                    >
                        { hang.shelveTime === "" && hang.surplus>=0 && 
                            <div style={{ marginLeft: "5px" }} className="danger-cell btn"> 删除</div>
                        } </Popconfirm>
                    <MyButton hang={hang}></MyButton>
                    {hang.isBan == 0 ?
                        <div className="danger btn" onClick={() => { banGoods(hang, 1) }} >禁用</div>
                        : <div className="success btn" onClick={() => { banGoods(hang, 0) }}>启用</div>}

                    {hang.supplier == null ? <div className="primary-cell btn" onClick={() => { showModal(hang) }}>补货</div> : ''}
                    <Modal title="补货" open={isModalOpen} footer={null} onCancel={() => (setIsModalOpen(false))}>

                        <InputNumber addonBefore="+" controls={false} onChange={(e) => { numChange(e) }} value={numbers}>

                        </InputNumber>

                        <Button block type="primary" style={{ marginTop: "20px" }}
                            disabled={numbers == 0 || numbers == null} onClick={() => { addNumber() }}> 补货</Button>
                    </Modal>
                </div>
            ),
        },

    ];

    /**
     * @param {*} props 
     */
    const addNumber = async () => {
        const res = await addGoods();
        if (res) {
            setNumbers(null);
        }
    }


    //补货数字框改变事件
    const numChange = (e) => {
        setNumbers(e);
    }

    //点击搜索按钮触发事件
    const onSearch = (value, _e, info) => {
        setLike((likeSelect) => ({ ...likeSelect, key: value }));
    }


    //补货弹出框 start
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [addId, setAddId] = useState("");
    const showModal = (props) => {
        setAddId(props.id);
        setIsModalOpen(true);
    };

    //补货弹出框 end

    //搜索框改变事件
    const onSearchData = () => {
        // setLike((likeSelect) => ({ ...likeSelect, key: myRef.current.input.value }));

        if (myRef.current.input.value == "" || myRef.current.input.value == null) {
            setLike((likeSelect) => ({ ...likeSelect, key: "" }));
        }
    }


    //根据条件获取数据
    const getData = async () => {
        setLoad((load) => ({ ...load, loading: true }));

        const goodData = await GetGoods({
            page: pages.page,
            limit: pages.limit,
            isBan: likeSelect.isBan,
            isShelve: likeSelect.isShelve,
            inventory: likeSelect.inventory,
            isDirectly: likeSelect.isDirectly,
            key: likeSelect.key
        });
        goodData?.data?.data.map((d, i) => d.Index = i + 1);
        setLoad((load) => ({ ...load, loading: false }));
        setLoad((load) => ({ ...load, isFirst: false }));
        if (goodData?.result === 0) {
            setTable(goodData.data);
            setPage((pages) => ({ ...pages, total: goodData.data.total }));
        }
    }

    //初始数据渲染及基础监听
    useEffect(() => {

        getData();

    }, [pages.page, likeSelect.isBan, likeSelect.isShelve, likeSelect.inventory, likeSelect.isDirectly, likeSelect.key]);


    //分页改变事件
    const pageChange = (props) => {
        setPage((pages) => ({ ...pages, page: props }));
    }



    //上下架按钮事件
    const shelveChange = async (props, num) => {
        setLoad((load) => ({ ...load, loading: true }));
        const res = await ShelveGoods({ ids: [props.id], isShelve: num });
        if (res.result === 0) {
            message.success("操作成功");
            getData();
        } else {
            message.error(res.message);
        }
    }


    //禁用/启用 1/0
    const banGoods = async (props, num) => {
        setLoad((load) => ({ ...load, loading: true }));
        const res = await BanGoods({ ids: [props.id], isBan: num });
        if (res.result === 0) {
            message.success("操作成功");
            getData();
        } else {
            message.error(res.message);
        }
    }


    //删除商品按钮事件
    const deleteGoods = async (props) => {
        setLoad((load) => ({ ...load, loading: true }));
        const res = await DeleteGoods({ id: props });
        if (res.result === 0) {
            message.success("操作成功");
            getData();
        } else {
            message.error(res.message);
        }
    }


    //补货
    const addGoods = async () => {
        setLoad((load) => ({ ...load, loading: true }));
        const res = await AddInventory({ id: addId, number: numbers });
        if (res.result === 0) {
            message.success("操作成功");
            setIsModalOpen(false);
            getData();
            return true
        } else {
            message.error(res.message);
        }
    }




    //删除旗袍确认 start
    const confirm = (props) => {
        deleteGoods(props)
    };
    const cancel = (e) => {
        console.log(e);
        message.error('已取消');
    };
    //删除旗袍确认 end

    const goAdd = () => {
        navigate("/goods/add");
    }


    return (
        <>

            <div className="Containers">
                <Skeleton active loading={load.isFirst} paragraph={{ rows: 15 }}>
                    <div className="goodsIndexContainer">
                        <div className="good-head">
                            <div><Button type="primary" onClick={() => { goAdd() }}>新增商品</Button></div>


                            <div>
                                <Search
                                    placeholder="输入商品名搜索"
                                    onSearch={onSearch}
                                    allowClear
                                    style={{
                                        width: 500,
                                    }}
                                    onChange={(e) => onSearchData(e)}
                                    ref={myRef}
                                />
                            </div>


                            <div>
                                <Checkbox.Group options={options} defaultValue={[]} onChange={onChange} />

                            </div>
                        </div>



                        <div className="good-data">

                            <Table dataSource={tableData.data} columns={columns} bordered pagination={false} loading={load.loading}
                                style={{ marginTop: "10px" }}
                                scroll={{
                                    y: "405px",
                                    x: "1450px"
                                }} />

                            <div className="page-layout">
                                <Pagination defaultCurrent={pages.page} total={pages.total} onChange={(value) => { pageChange(value) }} />
                            </div>
                        </div>
                    </div>
                </Skeleton>
            </div>
        </>
    )
}

export default GoodsIndex